import { Global, css } from '@emotion/react'
import {
	Box,
	Card,
	CardActions,
	CardContent,
	IconButton,
	Tooltip,
	Typography
} from '@mui/material'
import { useMutation, useQueryClient } from '@tanstack/react-query'
import dayjs from 'dayjs'
import {
	BriefcaseBusiness,
	CheckCircle,
	Clock,
	Eye,
	Plus,
	Trash
} from 'lucide-react'
import { useRouter } from 'next/navigation'
import { useEffect, useState } from 'react'
import { toast } from 'sonner'

import { type ITask, taskStatuses } from '@/types/task.types'

import { DASHBOARD_PAGES } from '@/config/pages-url.config'

import { taskService } from '@/services/tasks.service'

function getStatusIcon(status: number) {
	let icon = null
	switch (status) {
		case 0:
			icon = <Plus />
			break
		case 1:
			icon = <BriefcaseBusiness />
			break
		case 8:
			icon = <Trash />
			break
		case 9:
			icon = <CheckCircle />
			break
	}

	return icon !== null ? (
		<Tooltip
			title={taskStatuses[status]}
			placement='top'
		>
			{icon}
		</Tooltip>
	) : null
}

function getTimeLeft(deadline: dayjs.Dayjs | null) {
	if (!deadline) return [null, 'text.secondary']

	const diff = deadline.diff()
	if (diff <= 0) return ['Просрочена!', 'error.main']

	return [
		deadline.fromNow(),
		diff < 46800000 ? 'warning.main' : 'text.secondary'
	]
}

export function TaskMinCard({
	task,
	queryKey
}: {
	task: ITask
	queryKey: [string, string, number]
}) {
	const router = useRouter()
	const queryClient = useQueryClient()
	const [isHovered, setIsHovered] = useState(false)
	const [[timeLeft, color], setTimeLeft] = useState(() =>
		getTimeLeft(task.deadline)
	)

	useEffect(() => {
		if (task.deadline && task.status < 8 && task.deadline.diff() > 0) {
			const intervalId = setInterval(() => {
				setTimeLeft(getTimeLeft(task.deadline))
			}, 60000) // обновление каждую минуту

			return () => clearInterval(intervalId) // очистка при размонтировании
		}
	}, [task.deadline, task.status])

	const updateStatus = useMutation({
		mutationKey: ['task', 'update', task.id],
		mutationFn: async (status: number) =>
			await taskService.update(task.id, { ...task, status: status }),
		onSuccess: data => {
			queryClient.setQueryData(queryKey, (tasks: ITask[]) =>
				tasks.map(t => (t.id === data.id ? data : t))
			)
			toast.success('Статус задачи успешно обновлен!', {
				description: `"${data.title}": "${taskStatuses[task.status]}" -> "${taskStatuses[data.status]}"`
			})
		}
	})

	return (
		<>
			<Global
				styles={css`
					@keyframes pulse {
						0%,
						100% {
							transform: scale(1);
						}
						50% {
							transform: scale(1.2);
						}
					}
				`}
			/>
			<Card
				sx={{ maxWidth: 280, height: '100%' }}
				onMouseEnter={() => setIsHovered(true)}
				onMouseLeave={() => setIsHovered(false)}
			>
				<CardContent>
					<Typography
						gutterBottom
						variant='h5'
						component='div'
						sx={
							task.status < 8
								? {
										display: 'flex',
										alignItems: 'center',
										gap: 1
									}
								: {
										textDecoration: 'line-through',
										color: 'text.disabled',
										display: 'flex',
										alignItems: 'center',
										gap: 1
									}
						}
					>
						{getStatusIcon(task.status)}
						{task.title}
					</Typography>
					{timeLeft && task.status <= 8 && (
						<Tooltip
							title='Крайний срок выполнения'
							placement='left-start'
						>
							<Box
								sx={{
									display: 'flex',
									alignItems: 'center',
									gap: 1,
									color: color,
									marginBottom: 0.5
								}}
							>
								<div
									style={
										color === 'warning.main'
											? { animation: `pulse 2s ease-in-out infinite` }
											: {}
									}
								>
									<Clock size={18} />
								</div>
								<Typography variant='body2'>{timeLeft}</Typography>
							</Box>
						</Tooltip>
					)}
					<Typography
						variant='body2'
						color='text.secondary'
					>
						{task.description}
					</Typography>
				</CardContent>
				<CardActions
					sx={{
						opacity: isHovered ? 1 : 0,
						transition: 'opacity 0.3s'
					}}
				>
					{task.status === 0 && (
						<Tooltip title='Начать выполнение'>
							<IconButton
								color='primary'
								onClick={() => updateStatus.mutate(1)}
							>
								<BriefcaseBusiness />
							</IconButton>
						</Tooltip>
					)}
					{task.status <= 1 && (
						<Tooltip title='Подтвердить выполнение'>
							<IconButton
								color='success'
								onClick={() => updateStatus.mutate(9)}
							>
								<CheckCircle />
							</IconButton>
						</Tooltip>
					)}
					<Tooltip title='Подробнее'>
						<IconButton
							color='secondary'
							onClick={() => router.push(`${DASHBOARD_PAGES.TASK}${task.id}`)}
						>
							<Eye />
						</IconButton>
					</Tooltip>
				</CardActions>
			</Card>
		</>
	)
}
